<template>
  <a-modal
    wrapClassName="status-monitoring-dialog"
    destroyOnClose
    :width="'75vw'"
    v-model="dialogVisible"
    :footer="null"
    :maskClosable="false"
  >
    <div slot="title" class="status-monitoring-dialog-title">
      <span>服务器状态监控</span>
    </div>
    <div class="status-monitoring-dialog-wrapper">
      <div class="status-monitoring-triple">
        <div class="status-monitoring-triple-top">CPU</div>
        <div class="status-moitoring-chart" ref="cpuPieRef"></div>
      </div>
      <div class="status-monitoring-triple">
        <div class="status-monitoring-triple-top">内存</div>
        <div class="status-monitoring-triple-bottom">
          <div class="status-moitoring-storage">
            <span class="storage-ico"></span>
            <span class="storage-text">总内存:</span>
            <span>{{ totalNC }}</span>
          </div>
          <div class="operation-progress-info">
            <div class="operation-progress-info-left">
              <span>使用情况:</span>
              <span
                ><i>{{ useNC }}</i
                >/{{ totalNC }}G</span
              >
            </div>
            <div>{{ useNCPercent }}%</div>
          </div>
          <el-progress
            style="width: 100%"
            :percentage="useNCPercent"
            :text-inside="true"
            :stroke-width="12"
            :show-text="false"
          ></el-progress>
        </div>
      </div>
      <div class="status-monitoring-triple">
        <div class="status-monitoring-triple-top">服务器</div>
        <ul class="status-monitoring-server">
          <li v-for="(val, k) in serverObj" :key="k">
            <span class="server-obj-key">{{ serverDicData[k] }}:</span>
            <span
              class="server-obj-val"
              :class="[{ online: val == '1' }, { offline: val == '0' }]"
            >
              <template v-if="k == 'status'">
                {{ val == "1" ? "在线" : "离线" }}
              </template>
              <template v-else>
                {{ val }}
              </template>
            </span>
          </li>
        </ul>
      </div>
      <div class="status-monitoring-triple">
        <div class="status-monitoring-triple-top">
          <span>网络</span>
          <el-input
            v-model="netIP"
            placeholder="ip"
            class="domain-input-wrapper"
            :disabled="true"
            style="width: 230px"
            size="small"
          >
            <template slot="prepend">
              <el-select
                v-model="netVal"
                placeholder="类型"
                style="width: 100px; background: #fff"
                :disabled="historyView"
                size="small"
                @change="netChange"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in netOption"
                  :key="item.value"
                ></el-option>
              </el-select>
            </template>
          </el-input>
        </div>
        <div class="status-moitoring-chart" ref="netLineRef"></div>
      </div>
      <div class="status-monitoring-surplus">
        <div class="status-monitoring-triple-top">硬盘</div>
        <div class="disk-table-wrapper">
          <el-table
            :data="diskTable"
            height="100%"
            class="status-disk-info-table"
          >
            <el-table-column
              v-for="item in diskColumn"
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
              align="center"
            >
              <template slot-scope="{ row }">
                <template v-if="item.slot">
                  <div class="disk-table-progress">
                    <el-progress
                      type="circle"
                      :percentage="Number(row.yybfb).toFixed(0)"
                      width="40"
                      stroke-width="3"
                    ></el-progress>
                  </div>
                </template>
                <template v-else> {{ row[item.prop] }} </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script>
import * as echarts from "echarts";
import {
  getSourceStatus,
  severMangeList,
  selectNetChartList,
} from "@/api/resource/sever-mange";
export default {
  data() {
    return {
      pieSeriesData: [
        { value: 20.2, name: "用户使用率" },
        { value: 40, name: "系统使用率" },
        { value: 60, name: "当前空闲率" },
      ],
      // 核心数
      pieHxs: "",
      // 总内存
      totalNC: "",
      // 使用内存
      useNC: "",
      // 内存使用率
      useNCPercent: "",
      netVal: "0",
      netIP: "",
      netOption: [
        { value: "0", label: "第一网卡" },
        { value: "1", label: "第二网卡" },
        { value: "2", label: "第三网卡" },
        { value: "3", label: "第四网卡" },
      ],
      serverObj: {
        status: "在线",
        ip: "192.168.31.197",
        serverName: "LAPTOP-HUETGUUP",
        system: "LAPTOP-HUETGUUP",
        framework: "LAPTOP-HUETGUUP",
      },
      serverDicData: {
        status: "状态",
        ip: "服务器IP",
        serverName: "服务器名称",
        system: "操作系统",
        framework: "系统架构",
      },
      diskColumn: [
        { label: "盘符路径", prop: "pflj" },
        { label: "文件系统", prop: "wjxt" },
        { label: "盘符类型", prop: "pflx" },
        { label: "总大小", prop: "zdx" },
        { label: "可用大小", prop: "kydx" },
        { label: "已用大小", prop: "yydx" },
        { label: "已用百分比", prop: "yybfb", slot: "percentSlot" },
      ],

      diskTable: [
        {
          pflj: "d/usr/sotr",
          wjxt: "--",
          pflx: "--",
          zdx: "10G",
          kydx: "9G",
          yydx: "1G",
          yybfb: "10",
        },
      ],
      dialogVisible: false,
      queryParams: {
        skName: void 0,
        skIp: "",
      },
    };
  },
  computed: {},
  components: {},
  created() {},
  watch: {},
  mounted() {},
  beforeDestroy() {},
  destroyed() {},
  methods: {
    open(row) {
      this.dialogVisible = true;
      let obj = {
        skName: row.skName,
        skIp: row.skIp,
      };
      // 请求服务器状态
      severMangeList(obj).then((response) => {
        this.serverObj.status = response.rows.find(
          (item) => item.skIp == row.skIp
        ).isOnline;
      });
      this.getData(row.skName, row.skIp);
      this.getNetData(row.skName, row.skIp);
    },
    // 请求详情
    getData(name, ip) {
      getSourceStatus({ name, ip }).then((res) => {
        console.log("打印获取状态的数据", res);
        if (res.data.monitorCpu != null) {
          this.pieSeriesData.forEach((item) => {
            if (item.name == "用户使用率") {
              item.value = parseInt(res.data.monitorCpu.yhsyl);
            } else if (item.name == "系统使用率") {
              item.value = parseInt(res.data.monitorCpu.xtsyl);
            } else {
              item.value = parseInt(res.data.monitorCpu.dqkxl);
            }
          });
          this.pieHxs = res.data.monitorCpu.hxs;
        }
        if (res.data.monitorDisk[0] && res.data.monitorDisk[0] != null) {
          this.diskTable = res.data.monitorDisk;
        }
        if (res.data.monitorMemory != null) {
          //   this.memoryform = res.data.monitorMemory;
          this.totalNC = res.data.monitorMemory.znc;
          this.useNC = res.data.monitorMemory.yync;
          this.useNCPercent = res.data.monitorMemory.syl;
        }

        if (res.data.monitorServer) {
          //   this.severform = res.data.monitorServer;
          this.serverObj.ip = res.data.monitorServer.fwqip;
          this.serverObj.system = res.data.monitorServer.czxt;
          this.serverObj.framework = res.data.monitorServer.xtjg;
          this.serverObj.serverName = res.data.monitorServer.fwqmc;
        }

        this.$nextTick(() => {
          this.drawPie(this.pieSeriesData, this.pieHxs);
        });
      });
    },
    // 网卡信息
    getNetData(name, ip) {
      selectNetChartList({ name, ip }).then((res) => {
        console.log("获取网卡信息", res);
        if (res.code == 200) {
          this.netOption = res.data.map((item) => {
            return {
              ...item,
              label: item.name,
              value: item.name,
            };
          });
          if (res.data.length > 0) {
            this.netVal = this.netOption[0].label;
            this.netIP = this.netOption[0].ip;
            // 组装网卡折线数据
            let seriesData = [
              {
                name: "上传速度",
                data: this.netOption[0].speeds.map((item) => Number(item.scsd)),
                type: "line",
              },
              {
                name: "下载速度",
                data: this.netOption[0].speeds.map((item) => Number(item.xzsd)),
                type: "line",
              },
            ];
            let xData = Array.from(
              { length: this.netOption[0].speeds.length },
              (_v, k) => k + "s"
            );
            console.log(seriesData, xData);
            this.$nextTick(() => {
              this.drawLine(seriesData, xData);
            });
            // this.netOption[0].speeds
          } else {
            this.netVal = "";
            this.netIP = "";
          }
        }
      });
    },
    netChange(val) {
      this.netIP = this.netOption.find((item) => item.name == val).ip;
    },
    // 绘制cpu饼图
    drawPie(seriesData, hxs) {
      let chartDom = this.$refs.cpuPieRef;
      let myChart = echarts.init(chartDom);
      let option = {
        title: {
          text: ["{a|核心数:}", `{b|${hxs}}`].join(""),

          top: "16%",
          right: "13%",
          textStyle: {
            rich: {
              a: {
                color: "#333333",
                fontWeight: 400,
                fontSize: 16,
              },
              b: {
                color: "#1486F6",
                fontWeight: 400,
                fontSize: 16,
              },
            },
          },
        },
        tooltip: {
          trigger: "item",
          axisPointer: {
            type: "line", // 指示器类型（'line' 直线指示器；'shadow' 阴影指示器；'none' 无指示器；'cross' 十字准星指示器。）
            snap: false, // 坐标轴指示器是否自动吸附到点上。默认自动判断。
          },
          showContent: true, // 是否显示提示框浮层，默认显示
          alwaysShowContent: false, // 是否永远显示提示框内容，默认情况下在移出可触发提示框区域后一定时间后隐藏
          triggerOn: "mousemove", // 提示框触发的条件（'mousemove'，鼠标移动时触发；'click'，鼠标点击时触发；'mousemove|click'，同时鼠标移动和点击时触发；'none'，不在 'mousemove' 或 'click' 时触发）
          confine: false, // 是否将 tooltip 框限制在图表的区域内
          backgroundColor: "#fff", // 提示框浮层的背景颜色
          padding: 15, // 提示框浮层内边距，单位px
          position: "right",
          textStyle: {
            color: "#333", // 文字的颜色
            fontSize: 12,
            fontStyle: "normal", // 文字字体的风格（'normal'，无样式；'italic'，斜体；'oblique'，倾斜字体）
            fontWeight: "normal", // 文字字体的粗细（'normal'，无样式；'bold'，加粗；'bolder'，加粗的基础上再加粗；'lighter'，变细；数字定义粗细也可以，取值范围100至700）
          },
          formatter: function (data) {
            return (
              data.marker + data.name + " : " + data.percent.toFixed(2) + "%"
            );
          },
        },
        legend: {
          orient: "vertical",
          right: "right",
          y: "center",
          formatter: (name) => {
            let v;
            let total = this.pieSeriesData.reduce((prev, cur, index, arr) => {
              return prev + cur.value;
            }, 0);
            this.pieSeriesData.forEach((item) => {
              if (item.name === name) {
                v = item.value;
              }
            });
            return name + ": " + ((Number(v) / total) * 100).toFixed(2) + "%";
          },
        },
        color: ["#68E6F1", "#1486F6", "#48BAFF"],
        series: [
          {
            name: "",
            type: "pie",
            center: ["27%", "50%"],
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            labelLine: {
              show: false,
            },
            data: seriesData,
          },
        ],
      };

      option && myChart.setOption(option);
    },
    // 绘制折现图
    drawLine(seriesData, xData) {
      let chartDom = this.$refs.netLineRef;
      let myChart = echarts.init(chartDom);
      let option = {
        legend: {
          data: ["上传速度", "下载速度"],
          icon: "roundRect",
          right: 0,
          top: "5%",
        },
        tooltip: {
          trigger: "item",
          formatter(params) {
            console.log("params", params);
            return params.seriesName + ": " + params.value + "M/S";
          },
        },
        grid: {
          left: "12%",
          top: "20%",
          right: "5%",
          bottom: "10%",
        },
        color: ["#68E6F1", "#1486F6", "#48BAFF"],
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: xData,
          axisLine: {
            lineStyle: {
              color: "#979797",
            },
          },
        },
        yAxis: {
          show: true,
          name: "单位：M/S",
          type: "value",
          splitLine: {
            show: false,
          },
          axisLine: {
            lineStyle: {
              color: "#979797",
            },
          },
        },
        series: seriesData,
      };

      option && myChart.setOption(option);
    },
    // handleBeforeUnload (event) {
    //   this._beforeUnload_time = new Date().getTime()
    //   // 兼容火狐的做法
    //   event.preventDefault()
    //   event.returnValue = ''
    //   // 展示提示消息
    //   const message = '确定要离开吗？'
    //   event.returnValue = message
    //   return message
    // },
  },
};
</script>
<style lang="scss">
.status-monitoring-dialog {
  display: flex;
  justify-content: center;
  align-items: center;
  .ant-modal {
    top: 0;
  }
  .status-monitoring-dialog-title {
    span {
      position: relative;
      padding-left: 12px;
      font-size: 18px;
      color: #333333;
      line-height: 20px;
      &::before {
        content: "";
        position: absolute;
        width: 4px;
        height: 98%;
        top: 50%;
        transform: translateY(-50%);
        left: 0;
        background: #1486f6;
      }
    }
  }
  .status-monitoring-dialog-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    height: 570px;
    box-sizing: border-box;
    .status-monitoring-triple-top {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .status-monitoring-triple {
      width: 33%;
      height: 280px;
      box-sizing: border-box;
      background-color: rgba(242, 245, 248, 0.5);
      padding: 20px;
      display: flex;
      flex-direction: column;

      .status-monitoring-triple-bottom {
        flex: 1;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: center;
        // 内存
        .status-moitoring-storage {
          width: 100%;
          margin-bottom: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          .storage-ico {
            display: inline-block;
            width: 18px;
            height: 18px;
            background: url("../../assets/images/pieIco.png") no-repeat;
            background-size: 100% 100%;
          }
          .storage-text {
            margin: 0 6px;
          }
          span {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #333333;
            line-height: 20px;
            &:last-child {
              font-size: 18px;
              font-family: AlibabaPuHuiTi_2_85_Bold;
              color: #1486f6;
            }
          }
        }
        .operation-progress-info {
          width: 100%;
          display: flex;
          justify-content: space-between;
          margin-bottom: 12px;
          color: #333333;
          line-height: 20px;
          &-left {
            span {
              &:first-child {
                margin-right: 6px;
              }
              i {
                font-size: 18px;
                color: #1486f6;
                font-style: normal;
              }
            }
          }
        }
      }
      .status-monitoring-server {
        flex: 1;
        overflow: hidden;
        margin-bottom: 0;
        padding-top: 20px;
        padding-left: 0;
        li {
          list-style: none;
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          line-height: 20px;
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          &:last-child {
            margin-bottom: 0;
          }
          .server-obj-key {
            color: #777777;
          }
          .server-obj-val {
            color: #333333;
          }
          .online {
            position: relative;
            &::before {
              content: "";
              position: absolute;
              width: 8px;
              height: 8px;
              background: #34cc0c;
              border-radius: 50%;
              top: 50%;
              left: -18px;
              transform: translateY(-50%);
            }
          }
          .offline {
            position: relative;
            &::before {
              content: "";
              position: absolute;
              width: 8px;
              height: 8px;
              background: #909399;
              border-radius: 50%;
              top: 50%;
              left: -18px;
              transform: translateY(-50%);
            }
          }
        }
      }
      .status-moitoring-chart {
        flex: 1;
        overflow: hidden;
      }
    }
    .status-monitoring-surplus {
      width: 66.5%;
      height: 280px;
      box-sizing: border-box;
      background-color: rgba(242, 245, 248, 0.5);
      padding: 20px;
      display: flex;
      flex-direction: column;
      .disk-table-wrapper {
        flex: 1;
        overflow: hidden;
        margin-top: 20px;
        .status-disk-info-table {
          width: 100%;
          height: 100%;
          background-color: transparent;
          tr {
            background-color: transparent;
          }
          .disk-table-progress {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }
}
.disk-table-progress {
  .el-progress--circle .el-progress__text {
    font-size: 12px !important;
  }
}
</style>
